const connection = require('../db/mysql')

class OrderService {
    // 根据stadiumId和userId获取订单
    async getOne(stadiumId, userId) {
        let statement = 'SELECT * FROM `order` WHERE stadiumId = ? AND userId = ?;'
        let [ result ] = await connection.execute(statement, [stadiumId, userId])
        return result
    }
    // 根据id获取订单
    async getOneById(orderId) {
        let statement = 'SELECT * FROM `order` WHERE id = ?;'
        let [ result ] = await connection.execute(statement, [orderId])
        return result
    }
    // 插入订单
    async insertOrder(status, orderNo, userId, stadiumId, amount) {
        let statement = 'INSERT INTO `order`(status, orderNo, userId, stadiumId, amount) VALUES(?, ?, ?, ?, ?);'
        let params = [status, orderNo, userId, stadiumId, amount]
        let [ result ] = await connection.execute(statement, params)
        return result
    }
    // 结算订单 => 更新amount
    async updateAmount(cost, orderId) {
        let statement = 'UPDATE `order` SET amount = ?, status = 1, updateAt = NOW() WHERE id = ?;'
        let [ result ] = await connection.execute(statement, [cost, orderId])
        return result
    }
    // 重设订单
    async resetOrder(orderNo, orderId) {
        let statement = 'UPDATE `order` SET orderNo = ?, amount = 0, status = 0, createAt = NOW(), updateAt = NOW() WHERE id = ?;'
        let [ result ] = await connection.execute(statement, [orderNo, orderId])
        return result
    }
    // 获取订单列表 (分页)
    async list(userId, pageNum, pageSize) {
        let statement = `SELECT o.*, s.name FROM \`order\` o LEFT JOIN stadium s ON o.stadiumId = s.id WHERE o.userId = ? LIMIT ${pageNum}, ${pageSize};`
        let [ result ] = await connection.execute(statement, [userId])
        return result
    }
    // 获取订单总数
    async getTotal(userId) {
        let statement = 'SELECT COUNT(*) `total` FROM `order` WHERE userId = ?;'
        let [[ { total: result } ]] = await connection.execute(statement, [userId])
        return result
    }
    // 根据id删除订单
    async remove(orderId) {
        let statement = 'DELETE FROM `order` WHERE id = ?;'
        let [ result ] = await connection.execute(statement, [orderId])
        return result
    }
}

module.exports = new OrderService()